#!/usr/bin/env python

import os
import optparse
import time

myoptparser = optparse.OptionParser()
myoptparser.add_option('-f', '--filelist',help=" Supply a list of input files separated by commas",dest="f",metavar='FILELIST')
myoptparser.add_option('-i', '--histname',help=" Supply a hsitogram name with its ful path in the rootfile",dest="i",metavar='HISTNAME')
myoptparser.add_option('-r', '--roodir',help=" The directory structure where your histogram resides",dest="r",metavar='ROOTDIR')
myoptparser.add_option('-u', '--superimpose',help=" superimpose the histograms",dest="u",metavar='FLAG',action='store_true')
myoptparser.add_option('-s', '--stack',help=" stack the histograms",dest="s",metavar='FLAG',action='store_true')
myoptparser.add_option('-k', '--kolor',help=" use FillColor for histograms",dest="k",metavar='FLAG',action='store_true')


(options, args) = myoptparser.parse_args()

if not options.u and not options.s:
  print "Commandline Error! -u or -s must be supplied"
  os.sys.exit(-1)

if not options.f or not options.i or not options.r:
  print "Commandline error! -f -i -r options are mandatories.."
  os.sys.exit(-1)


from ROOT import TH1F,TFile,THStack,gDirectory,gROOT,TCanvas,kRed,kGreen,kBlue,kTeal,kMagenta,kCyan,kOrange



kolorList=[kRed,kBlue,kGreen,kTeal,kMagenta,kCyan,kOrange]
g_xcnFile='xcns.dat'
AllowedSampleList=[]#make an allowed samplelist from xcn file
Filelist=[]#my filelist
histoname=''#my histograms' name to stack
roodir=''
xcnMap={}#my cross section map : {hname:xcn}
xcnRooFileMap={}
def ReadXcnFile():
  linectr=0
  xcnfile=open(g_xcnFile)
  while True:
    linectr+=1
    aline=xcnfile.readline()
    if aline.find("#")==0:
      continue
    if not aline:
      break
    if len(aline.split('='))!=2:
      print "ERROR in xcnfile. Bad line at: "+str(linectr)
      os.sys.exit(-1)
    xcn_val=float(aline.split('=')[1])
    sname=aline.split('=')[0]
    AllowedSampleList.append(sname)
    xcnMap[sname]=xcn_val
  return
#********************************************************

def HandleRootFiles(f_option):#get a filelist from commandline & check if their names consists of a specific samplename as defined in g_SampleList. if ok then add them in a filelist
  myfilelist=f_option.split(',')
  for sample in AllowedSampleList: 
    for F in myfilelist:
      if F.find(sample)!=-1:#if the file has samplename as substring... add it to the container
        Filelist.append(F)
        xcnRooFileMap[F]=xcnMap[sample]
  return

def stackHists(f_option,histname):#get the histogram name  with its directory in the root file e.g : E6-1/ptJ0. All files must have this directory structure
  HandleRootFiles(f_option)#fill the global filelist
  mystack=THStack("mystack","Superimposed Histograms")
  cnvs=TCanvas("cnvs","Superimposed Histograms")
  ofile=TFile(options.i+"_stack.root","RECREATE")
  ctr=-1
  for F in Filelist:
    ctr+=1
    roofile=TFile(F,"READ")
    ahist=roofile.Get(options.r+'/'+options.i)
    if ahist==None:
      print "ERROR*** returned NONE type for the histogram: "+options.i+" in the file: "+F+"/"+options.r
      os.sys.exit(-8)
    gROOT.cd()
    thehist=ahist.Clone()
    if options.k:
      thehist.SetFillColor(kolorList[ctr])
    effhist=roofile.Get(options.r+"/eff")
    N=effhist.GetBinContent(3)
    thehist.Scale(xcnRooFileMap[F]/N)
    thehist.SetLineColor(kolorList[ctr])
    mystack.Add(thehist)
    roofile.Close()
  #mystack.ls()
  if options.u:
    mystack.Draw("nostack")
    print "Superimposing: "+options.i+"/"+F+" to the stack"
  elif options.s:
    print "Adding: "+options.i+"/"+F+" to the stack"
    mystack.Draw()
  else:
    print "Commandline Error.. -u or -s must be supplied"
    os.sys.exit(-1)
  ofile.cd()
  cnvs.Write()
  return cnvs


ReadXcnFile()
mystak=stackHists(options.f,options.i)
#print AllowedSampleList
#print Filelist
#print xcnRooFileMap
